from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import os
import yaml

router = APIRouter(prefix="/api/agent", tags=["Agent Management"])

# 配置文件目录
CONFIG_DIR = os.path.join(os.path.dirname(__file__), "agent_config")

# 确保配置目录存在
os.makedirs(CONFIG_DIR, exist_ok=True)

class SupervisorConfig(BaseModel):
    """监管者配置模型"""
    supervisor: dict

class AgentCreateRequest(BaseModel):
    """创建代理请求模型
    Attributes:
        supervisor: 监管者配置字典，包含代理初始化参数
    """
    yaml_name: str
    supervisor: dict

class AgentDeleteRequest(BaseModel):
    """删除代理请求模型
    Attributes:
        yaml_name: 要删除的配置文件名
    """
    yaml_name: str

class AgentUpdateRequest(BaseModel):
    """更新代理请求模型
    Attributes:
        yaml_name: 要更新的配置文件名
        supervisor: 新的监管者配置
    """
    yaml_name: str
    supervisor: dict

@router.get("/list")
async def list_agents():
    """获取所有代理配置文件列表
    - 返回结构:包含所有yaml文件名的列表
    """
    try:
        # 获取agent_config目录下所有yaml文件
        yaml_files = [f for f in os.listdir(CONFIG_DIR) if f.endswith(".yaml") or f.endswith(".yml")]
        return {"code": 200, "message": "success", "data": yaml_files}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/create")
async def create_agent(request: AgentCreateRequest):
    """创建新的任务管理代理
    - 参数校验:自动通过Pydantic模型校验
    - 配置保存:将配置以yaml格式保存到agent_config目录
    """
    try:
        # 使用supervisor中的name字段作为文件名
        yaml_name = f"{request.yaml_name}.yaml"
        file_path = os.path.join(CONFIG_DIR, yaml_name)
        
        # 将配置写入yaml文件
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(request.supervisor, f, default_flow_style=False, allow_unicode=True)
        
        return {"code": 200, "message": "success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/delete")
async def delete_agent(request: AgentDeleteRequest):
    """删除指定代理配置文件
    - 参数校验:yaml_name必须存在
    """
    try:
        file_path = os.path.join(CONFIG_DIR, request.yaml_name)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail=f"配置文件 {request.yaml_name} 不存在")
        
        # 删除文件
        os.remove(file_path)
        
        return {"code": 200, "message": "success"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/update")
async def update_agent(request: AgentUpdateRequest):
    """更新指定代理配置
    - 参数校验:yaml_name必须存在
    - 配置更新:更新对应yaml文件内容
    """
    try:
        file_path = os.path.join(CONFIG_DIR, request.yaml_name)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail=f"配置文件 {request.yaml_name} 不存在")
        
        # 更新配置文件
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(request.supervisor, f, default_flow_style=False, allow_unicode=True)
        
        return {"code": 200, "message": "success"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/query")
async def query_agent(yaml_name: str):
    """查询单个代理配置
    - 参数校验:yaml_name必须存在
    - 数据获取:从yaml文件读取代理配置
    - 返回结构:包含代理详细配置信息
    """
    try:
        file_path = os.path.join(CONFIG_DIR, yaml_name)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail=f"配置文件 {yaml_name} 不存在")
        
        # 读取yaml文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            supervisor_config = yaml.safe_load(f)
        
        return {"yaml_name": yaml_name, "supervisor": supervisor_config}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))